/* eslint-disable react/jsx-indent-props */
/* eslint-disable react/jsx-indent */
/* eslint-disable @typescript-eslint/indent */
/* eslint-disable indent */
import React, { memo, useCallback, useEffect, useRef, useState } from 'react';
import { Button, Divider, Form, Input, message, Popconfirm, Spin, Tooltip, Row } from 'antd';
import { Split, Collapse } from '@/molecules';
import { useCollapse, useRequest, defaultFormatResult } from '@/hooks';
import cn from 'classnames';
import moment from 'moment';
import LimitInput from '@/components/LimitInput';

import { debounce } from 'lodash';
import RecordButton from '@/pages/Recruitment/containers/RecordButton';
import { usePrepareAlert } from '../hooks';
import { FormLayout } from '../components';
import { ArrangeDetail, BottomAction, ConclusionRadioGroup, PrepareAlert } from '../containers';
import { generateRecordConclusionOption } from '../utils/interview';

import styles from './InterviewRecord.less';
import {
    getInterviewAudioRecordState,
    changeInterviewAudioRecordState,
    resetInterviewRecordState,
    saveQuestion,
    deleteQuestion,
    saveAnswer,
    saveComment,
    getOtherQuestions
} from '../services';

const { Panel } = Collapse;
const { TextArea } = Input;

const SAVE_METHOD_MAPPING = {
    question: saveQuestion,
    answer: saveAnswer,
    comment: saveComment
};

const evaluationFormLayout = {
    wrapperCol: { span: 18 },
    labelCol: { span: 6 }
};

const hintList = {
    1: '当前已有录音进行中！',
    2: '当前已有录音！',
    3: '获取录音状态失败，请重试！'
};

const Toolbar = ({ children }) => {
    const style = { height: 40, marginBottom: 8 };
    return (
        <Row type="flex" align="middle" style={style}>
            {children}
        </Row>
    );
};

const Label = ({ value, colon = false }) => {
    const style = { dispaly: 'inline-flex', lineHeight: '22px', fontWeight: 500, color: 'rgba(0,0,0,0.65)' };
    return <div style={style}>{value + (colon ? '：' : '')}</div>;
};

const firstUpper = word => word.replace(/^\S/, s => s.toUpperCase());

const editFlagName = type => `is${firstUpper(type)}Edit`;

const formFiledName = (index, type, contentName) => {
    const common = `interviewQuestion[${index}].${type}`;
    if (contentName) {
        return `${common}.${contentName}`;
    }
    return common;
};

const Question = memo(({ form, value = [], onChange, getRecordState = () => null, arrangeId }) => {
    const [formList, setFormList] = useState([]);
    const { getFieldDecorator, validateFields, getFieldValue, setFieldsValue, getFieldError } = form;
    const genUUID = useCallback(
        (length = 14) =>
            Number(
                Math.random()
                    .toString()
                    .substr(3, length) + Date.now()
            ).toString(36),
        []
    );

    const onAddQuestion = () => {
        const newFormList = getFieldValue('interviewQuestions');
        newFormList.push({
            isNew: true,
            isEqual: true,
            isQuestionEdit: true,
            isAnswerEdit: true,
            isCommentEdit: true,
            key: genUUID()
        });
        onChange(newFormList);
    };

    // 编辑/取消编辑
    const handleToggleEdit = useCallback(
        (index, type) => {
            const newFormList = getFieldValue('interviewQuestions');
            const flagName = editFlagName(type);
            const oldItem = newFormList[index];
            newFormList[index] = {
                ...oldItem,
                [flagName]: !oldItem[flagName]
            };
            onChange(newFormList);
        },
        [onChange]
    );

    /**
         interviewQuestion[${index}].submitCheck中的validator设置为提交验证，因而会出现，数据更改了不重新验证的问题，
         设置validator设置为提交验证的理由：实时验证,会出现开始录音，就检查出错误，同时触发到底下输出框的验证
         1.提交验证，出现错误提示
         2.操作数据，错误提示还存在
         3.此处手动进行数据更改校验
        */
    const recheckCheckField = useCallback(index => {
        const submitCheckFieldName = formFiledName(index, 'submitCheck');
        const error = getFieldError(submitCheckFieldName);
        if (error?.length) {
            validateFields([submitCheckFieldName]);
        }
    }, []);

    const onQuestionRecord = async (item, index) => {
        if (item[editFlagName('question')] || item.loading) return;

        const newFormList = formList.slice();
        if (!item.isRecord) {
            newFormList[index] = {
                ...newFormList[index],
                loading: true
            };
            onChange(newFormList);
            const recordState = await getRecordState(1);
            if ([0, 2].includes(recordState)) {
                message.error(
                    recordState === 0 ? '当前未开始录音，不可标记录音时间！' : '当前录音已结束，不可标记录音时间'
                );
                newFormList[index] = {
                    ...newFormList[index],
                    loading: false
                };
                onChange(newFormList);
                return;
            }
        }
        let answerTimes = item.answer && item.answer.answerTimes ? item.answer.answerTimes : [];
        if (item.isRecord) {
            const len = answerTimes.length;
            answerTimes[len - 1] = {
                ...answerTimes[len - 1],
                endTime: new Date().getTime()
            };
        } else {
            answerTimes.push({
                startTime: new Date().getTime()
            });
        }
        answerTimes = answerTimes.map((time, i) => ({
            ...time,
            sort: i + 1
        }));
        newFormList[index] = {
            ...newFormList[index],
            answer: {
                ...(newFormList[index].answer || {}),
                answerTimes
            },
            isRecord: !item.isRecord,
            loading: false
        };
        onChange(newFormList);
        recheckCheckField(index);
    };

    const onDeleteRecordTime = (item, index, listIndex) => {
        if (item.isRecord) {
            message.error('请先停止当前录音');
            return;
        }
        const newFormList = formList.slice();
        const { answer = {} } = newFormList[index];
        let { answerTimes = [] } = answer;
        answerTimes.splice(listIndex, 1);
        answerTimes = answerTimes.map((time, i) => ({
            ...time,
            sort: i + 1
        }));
        newFormList[index] = {
            ...newFormList[index],
            answer: {
                ...(newFormList[index].answer || {}),
                answerTimes
            }
        };
        onChange(newFormList);
    };

    // 确定
    const handleConfirm = useCallback(
        debounce((index, type, contentName) => {
            const fieldName = formFiledName(index, type, contentName);
            const fieldValue = getFieldValue(fieldName);

            validateFields([fieldName], err => {
                if (!err) {
                    const newFormList = getFieldValue('interviewQuestions');

                    const questionId = newFormList[index].id;

                    const params = contentName
                        ? { id: newFormList[index][type]?.id, questionId, [contentName]: fieldValue }
                        : { id: questionId, [type]: fieldValue };
                    SAVE_METHOD_MAPPING[type]({ arrangeId, ...params }).then(res => {
                        const id = res.data;
                        // 赋值方式区分
                        let nextValue = { [type]: fieldValue, id };

                        // 根据这个判断是不是对象（answer,comment）
                        if (contentName) {
                            nextValue = {
                                [type]: {
                                    ...(newFormList[index][type] || {}),
                                    [contentName]: fieldValue,
                                    id
                                }
                            };
                        }
                        newFormList[index] = {
                            ...newFormList[index],
                            ...nextValue,
                            [editFlagName(type)]: false
                        };

                        onChange(newFormList);
                        recheckCheckField(index);
                    });
                }
            });
        }, 400),
        [onChange]
    );

    const onDeleteQuestion = async i => {
        const lists = getFieldValue('interviewQuestions');
        const questionId = lists[i].id;
        if (questionId) {
            await deleteQuestion(questionId);
        }
        // eslint-disable-next-line guard-for-in,no-restricted-syntax
        for (const index in lists) {
            const nIndex = Number(index);
            if (nIndex >= i && lists[nIndex + 1]) {
                setFieldsValue({
                    [`interviewQuestion[${nIndex}]`]: lists[nIndex + 1]
                });
            }
        }
        const newFormList = formList.slice();
        newFormList.splice(i, 1);
        onChange(newFormList);
    };

    // 取消编辑问题
    const handleCancelQuestion = useCallback(
        index => {
            const type = 'question';
            const lastValue = getFieldValue('interviewQuestions')?.[index][type];
            if (lastValue) {
                handleToggleEdit(index, type);
            } else {
                onDeleteQuestion(index);
            }
        },
        [onDeleteQuestion, handleToggleEdit]
    );

    useEffect(() => {
        setFormList(value);
    }, [value]);

    // 头部 编辑中 按钮
    const renderEditingTitleButton = useCallback(
        (item, index) => (
            <div>
                <Tooltip placement="top" title="取消">
                    <i
                        className={cn('iconfont iconcancel_o', styles.iconHover)}
                        onClick={() => {
                            handleCancelQuestion(index);
                        }}
                    />
                </Tooltip>
                <Divider type="vertical" />
                <Tooltip placement="top" title="确定">
                    <i
                        className={cn('iconfont iconconfirm_o', styles.iconHover)}
                        onClick={() => {
                            handleConfirm(index, 'question');
                        }}
                    />
                </Tooltip>
            </div>
        ),
        [handleCancelQuestion, handleConfirm]
    );

    // 头部 编辑中
    const renderEditingTitle = useCallback(
        (item, index) => (
            <>
                <Form.Item>
                    {getFieldDecorator(formFiledName(index, 'question'), {
                        initialValue: item.question || '',
                        rules: [
                            { required: true, message: '请输入自定义问题标题!', whitespace: true },
                            { max: 200, message: '自定义问题不能超过100个字符' }
                        ]
                    })(<Input style={{ marginLeft: '8px', width: '600px' }} autoComplete="off" maxLength={100} />)}
                </Form.Item>
                {renderEditingTitleButton(item, index)}
            </>
        ),
        [renderEditingTitleButton]
    );

    // 头部 浏览中 按钮
    const renderBrowsingTitleButton = useCallback(
        (item, index) => {
            const { isEqual, isNew, createUserName } = item || {};
            if (!isEqual) {
                return <span className={styles.light}>{createUserName}</span>;
            }
            if (isNew) {
                return (
                    <div>
                        <i
                            onClick={() => handleToggleEdit(index, 'question')}
                            className={cn('iconfont iconlistfunction_edit_icon_default', styles.iconHover)}
                        />
                        <Divider type="vertical" />
                        <Popconfirm
                            title="确定是否删除?"
                            onConfirm={() => {
                                onDeleteQuestion(index);
                            }}
                        >
                            <i className={cn('iconfont iconDeleteIcon', styles.deleteIcon, styles.iconCursor)} />
                        </Popconfirm>
                    </div>
                );
            }
            return null;
        },
        [handleToggleEdit, onDeleteQuestion]
    );

    // 头部 浏览中
    const renderBrowsingTitle = useCallback(
        (item, index) => {
            const { question } = item || {};
            return (
                <>
                    <span className={styles.question} title={question}>
                        {question}
                    </span>
                    {renderBrowsingTitleButton(item, index)}
                </>
            );
        },
        [renderBrowsingTitleButton]
    );

    // 头部
    const renderTitle = useCallback(
        (item, index) => {
            if (item[editFlagName('question')]) {
                return renderEditingTitle(item, index);
            }
            return renderBrowsingTitle(item, index);
        },
        [renderEditingTitle, renderBrowsingTitle]
    );

    // 录音按钮
    const renderRecordButton = useCallback(
        (item, index) => {
            const { isQuestionEdit, loading, isRecord } = item || {};
            let classes = cn(styles.questionRecordButtonIconWrap, {
                [styles.unQuestionRecordBtnIcon]: isQuestionEdit
            });
            if (isRecord) {
                classes = styles.questionRecordButtonIconing;
            }
            return (
                <div style={{ display: 'inline-flex' }}>
                    <Spin spinning={!!loading}>
                        <div
                            className={styles.questionRecordButtonWrap}
                            onClick={onQuestionRecord.bind(null, item, index)}
                        >
                            <div className={classes}>
                                <i className={`iconfont ${isRecord ? 'iconstop_record_Icon' : 'iconrecordIcon'}`} />
                            </div>
                            {isRecord ? '点击停止录音' : '点击开始录音'}
                        </div>
                    </Spin>
                </div>
            );
        },
        [onQuestionRecord]
    );

    // 录音内容
    const renderRecordContent = useCallback(
        (item, index) => {
            const { answer } = item || {};
            if (!answer?.answerTimes?.length) {
                return null;
            }
            return answer.answerTimes.map((l, i) => (
                <div key={l.startTime} className={styles.questionRecordDateItem}>
                    <div className={styles.questionRecordDateItemWrap}>
                        <i className="iconfont iconlistfunciton_soundclip_icon_default" />
                        {`${moment(l.startTime).format('HH:mm:ss')} - ${
                            l.endTime ? moment(l.endTime).format('HH:mm:ss') : ''
                        }`}
                        <Popconfirm
                            title="确定是否删除?"
                            onConfirm={() => {
                                onDeleteRecordTime(item, index, i);
                            }}
                        >
                            <i className={cn('iconfont iconDeleteIcon', styles.questionRecordDeleteIcon)} />
                        </Popconfirm>
                    </div>
                </div>
            ));
        },
        [onDeleteRecordTime]
    );

    // 录音
    const renderRecord = useCallback(
        (item, index) => {
            const { isEqual } = item || {};
            if (!isEqual) {
                return null;
            }
            return (
                <>
                    <Toolbar>
                        <Label value="答复录音" colon />
                        {renderRecordButton(item, index)}
                    </Toolbar>
                    <div className={styles.questionRecordDateList}>{renderRecordContent(item, index)}</div>
                </>
            );
        },
        [renderRecordButton, renderRecordContent]
    );

    // 回答 浏览态 按钮
    const renderBrowsingReplyButton = useCallback(
        (item, index, type) => {
            const { isEqual } = item || {};
            const contentName = `${type}Content`;
            const val = item?.[type]?.[contentName];
            const SHOW_MAPPING = {
                answer: isEqual,
                comment: isEqual || !!val
            };
            if (SHOW_MAPPING[type]) {
                return <Button onClick={() => handleToggleEdit(index, type)}>编辑</Button>;
            }
            return null;
        },
        [handleToggleEdit]
    );

    // 回答 编辑态 按钮
    const renderEditingReplyButton = useCallback(
        (item, index, type) => {
            const contentName = `${type}Content`;
            const val = item?.[type]?.[contentName];
            const cancelDisplay = {
                answer: !!val,
                comment: !item?.isEqual || !!val
            };
            const save = (
                <Button type="primary" onClick={() => handleConfirm(index, type, contentName)}>
                    保存
                </Button>
            );
            const cancel = <Button onClick={() => handleToggleEdit(index, type)}>取消</Button>;
            if (cancelDisplay[type]) {
                return <Split space>{[cancel, save]}</Split>;
            }
            return save;
        },
        [handleConfirm, handleToggleEdit]
    );

    // 回答 头部
    const renderAnswerToolbar = useCallback(
        (item, index) => {
            const type = 'answer';
            const flagName = editFlagName(type);
            const flag = item?.[flagName];
            const btn = flag
                ? renderEditingReplyButton(item, index, type)
                : renderBrowsingReplyButton(item, index, type);
            const tip = item?.isEqual && flag && (
                <div className={styles.light} style={{ fontSize: '12px' }}>
                    内容保存后，其他面谈参与人将可看到您编辑的内容
                </div>
            );
            return (
                <>
                    <Toolbar>
                        <div style={{ flex: 1 }}>
                            <Label value="新员工答复" />
                            {tip}
                        </div>
                        {btn}
                    </Toolbar>
                </>
            );
        },
        [renderEditingReplyButton, renderBrowsingReplyButton]
    );

    // 回答 内容
    const renderAnswerContent = useCallback((item, index) => {
        const type = 'answer';
        const contentName = `${type}Content`;
        const flagName = editFlagName(type);
        const contentFieldName = formFiledName(index, type, contentName);
        const val = item?.[type]?.[contentName] ?? '';
        if (item?.[flagName]) {
            return getFieldDecorator(contentFieldName, {
                initialValue: val,
                rules: [
                    { required: true, message: '请输入新员工答复!', whitespace: true },
                    { max: 2000, message: '新员工答复不能超过2000个字符' }
                ]
            })(
                <LimitInput
                    area
                    maxLength={2000}
                    placeholder="请输入新员工答复"
                    autoSize={{ minRows: 4, maxRows: 4 }}
                />
            );
        }
        return (
            <div className={styles.browsingContainer}>
                {val.split('\n').map(show => (
                    <span>{show}</span>
                ))}
            </div>
        );
    }, []);

    // 回答
    const renderAnswer = useCallback(
        (item, index) => {
            const { isEqual, answer } = item || {};
            if (!isEqual && !answer?.answerContent) {
                return null;
            }
            return (
                <Form.Item>
                    {renderAnswerToolbar(item, index)}
                    {renderAnswerContent(item, index)}
                </Form.Item>
            );
        },
        [renderAnswerToolbar, renderAnswerContent]
    );

    // 评估 头部
    const renderCommentToolbar = useCallback(
        (item, index) => {
            const type = 'comment';
            const flagName = editFlagName(type);
            const isEqual = item?.isEqual;
            const contentName = `${type}Content`;
            const val = item?.[type]?.[contentName];
            const flag = item?.[flagName];
            const btn = flag
                ? renderEditingReplyButton(item, index, type)
                : renderBrowsingReplyButton(item, index, type);
            return (
                <>
                    <Toolbar>
                        <Row type="flex" style={{ flex: 1 }} align="middle">
                            <Label value="评估" />
                            {!isEqual && !val && !flag && (
                                <Button onClick={() => handleToggleEdit(index, type)} style={{ marginLeft: 12 }}>
                                    添加评估
                                </Button>
                            )}
                        </Row>
                        {btn}
                    </Toolbar>
                </>
            );
        },
        [renderEditingReplyButton, renderBrowsingReplyButton, handleToggleEdit]
    );

    // 评估 内容
    const renderCommentContent = useCallback((item, index) => {
        const type = 'comment';
        const contentName = `${type}Content`;
        const flagName = editFlagName(type);
        const contentFieldName = formFiledName(index, type, contentName);
        const val = item?.[type]?.[contentName] ?? '';
        if (!item?.isEqual && !val && !item?.[flagName]) {
            return null;
        }
        if (item?.[flagName]) {
            return getFieldDecorator(contentFieldName, {
                initialValue: val,
                rules: [
                    { required: item?.isEqual, message: '请输入评估!', whitespace: true },
                    { max: 1000, message: '评估不能超过1000个字符' }
                ]
            })(<LimitInput area maxLength={1000} autoSize={{ minRows: 4, maxRows: 4 }} placeholder="请输入评估" />);
        }
        return (
            <div className={styles.browsingContainer}>
                {val.split('\n').map(show => (
                    <span>{show}</span>
                ))}
            </div>
        );
    }, []);

    // 评估
    const renderComment = useCallback(
        (item, index) => (
            <Form.Item>
                {renderCommentToolbar(item, index)}
                {renderCommentContent(item, index)}
            </Form.Item>
        ),
        [renderCommentToolbar, renderCommentContent]
    );

    return (
        <>
            {formList.map((item, index) => (
                <Form.Item className={styles.interviewQuestionFormItem} key={item.id || item.key}>
                    {getFieldDecorator(`interviewQuestion[${index}].submitCheck`, {
                        validateTrigger: 'onSubmit', // 设置进行表单验证的时机为onSubmit
                        force: true,
                        rules: [
                            {
                                validator(_, interviewQuestion, callback) {
                                    const formItem = getFieldValue('interviewQuestions')?.[index];
                                    if (
                                        formItem?.[editFlagName('question')] ||
                                        formItem?.[editFlagName('answer')] ||
                                        formItem?.[editFlagName('comment')]
                                    ) {
                                        callback('请完成自定义问题编辑');
                                        return;
                                    }
                                    if (formItem?.isRecord) {
                                        callback('当前录音正在执行！');
                                        return;
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(
                        <div className={styles.questionWrap}>
                            <div className={styles.questionHeader}>
                                <span>{index + 1}.</span>
                                <div className={styles.questionHeaderContent}>{renderTitle(item, index)}</div>
                            </div>
                            <div className={styles.questionContent}>
                                {renderRecord(item, index)}
                                {renderAnswer(item, index)}
                                {renderComment(item, index)}
                                <div
                                    className={cn({ [styles.questionContentModal]: item[editFlagName('question')] })}
                                ></div>
                            </div>
                        </div>
                    )}
                </Form.Item>
            ))}
            <div className={styles.addQuestion} onClick={onAddQuestion}>
                + 添加问题
            </div>
        </>
    );
});
const Evaluation = memo(({ form, conclusions }) => {
    const { getFieldDecorator } = form;
    return (
        <Form {...evaluationFormLayout} className={styles.evaluationFormWrap} hideRequiredMark>
            <Form.Item label="结论">
                {getFieldDecorator('evaluateResult.resultType', {
                    initialValue: conclusions[0]
                })(<ConclusionRadioGroup conclusions={conclusions} />)}
            </Form.Item>
            <Form.Item label=" " colon={false}>
                {getFieldDecorator('evaluateResult.resultContent', {
                    initialValue: '',
                    rules: [
                        { required: true, message: '请输入评价', whitespace: true },
                        { max: 500, message: '评价不能超过500个字符' }
                    ]
                })(
                    <TextArea
                        placeholder="请输入评价"
                        style={{ width: 340 }}
                        autoSize={{ minRows: 3, maxRows: 3 }}
                        maxLength={500}
                    />
                )}
            </Form.Item>
        </Form>
    );
});

const currentUserCode = JSON.parse(localStorage.getItem('user') ?? null)?.employeeCode;
const isCurrentUser = code => code === currentUserCode;

const formatComment = source => (source || []).find(commentItem => isCurrentUser(commentItem.createUser)) || {};
const map = { weekly: 'W', monthly: 'M', quarterly: 'Q' };
const Record = ({ form, data }) => {
    const { activeKey, onChange, openAll } = useCollapse(['1', '2', '3'], []);
    const { interviewPrepareVO, period } = data || {};
    const { probationInterviewArrangeVO } = interviewPrepareVO || {};
    const { id: arrangeId, interviewType } = probationInterviewArrangeVO || {};
    const { getFieldDecorator, getFieldValue, setFieldsValue } = form;
    const scrollWrapRef = useRef();
    const recordButtonRef = useRef();
    const onChangeRecordState = useCallback(async (recordState = 1) => {
        try {
            await changeInterviewAudioRecordState({
                arrangeId,
                recordState
            });
            if (recordState === 1) {
                message.success('已开启录音，同时也可针对自定义问题进行单独录音。');
            }
            if (recordState === 2) {
                const interviewQuestions = form.getFieldValue('interviewQuestions');
                const newInterviewQuestions = interviewQuestions.map(item => {
                    if (!item.answer || !item.answer.answerTimes || !item.answer.answerTimes.length) {
                        return item;
                    }
                    return {
                        ...item,
                        isRecord: false,
                        answer: {
                            ...item.answer,
                            answerTimes: item.answer.answerTimes.map(time => {
                                if (time.endTime) return time;
                                return {
                                    ...time,
                                    endTime: new Date().getTime()
                                };
                            })
                        }
                    };
                });
                form.setFieldsValue({
                    interviewQuestions: newInterviewQuestions
                });
                form.validateFields(['interviewQuestion']);
            }
        } catch (e) {
            console.log(e);
        }
    }, []);
    const getRecordState = useCallback(async recordType => {
        try {
            const { data: ret, code } = await getInterviewAudioRecordState({
                arrangeId,
                recordType
            });
            return code === 10000 ? ret : 3;
        } catch (e) {
            console.log(e);
            return 3;
        }
    }, []);

    const getSubmitValues = React.useCallback(async values => {
        const { evaluateResult, interviewQuestions = [] } = values;
        const next = {
            arrangeId,
            evaluateResult,
            interviewQuestions,
            ...(recordButtonRef.current ? await recordButtonRef.current.getRecordInfo() : {})
        };
        const ret = {
            action: 'probationInterviewProcedure',
            status: data?.status,
            interviewProcedureSaveDTO: next
        };
        return ret;
    }, []);

    // 轮询
    const { run: runPolling, cancel: cancelPolling } = useRequest(() => getOtherQuestions(arrangeId), {
        ...defaultFormatResult,
        manual: true,
        pollingInterval: 5000,
        onSuccess(ret) {
            if (!(ret instanceof Array)) {
                return;
            }
            let nextFormList = (getFieldValue('interviewQuestions') || []).slice();
            // 为了减少render的次数
            let render = false;
            ret.forEach(item => {
                const { id: newId, createUserName, question: newQuestion, answer: newAnswer } = item || {};
                const oldIndex = nextFormList.findIndex(old => old.id === newId);
                // 新增
                if (oldIndex === -1) {
                    const len = nextFormList.push({ ...item, comment: {} });
                    message.info(`${createUserName} 新增了自定义问题 ${len}`);
                    render = true;
                } else {
                    // 更新
                    const old = nextFormList[oldIndex] || {};
                    const { question: oldQuestion, answer: oldAnswer } = old;
                    const oldAnswerContent = oldAnswer?.answerContent;
                    const newAnswerContent = newAnswer?.answerContent;
                    if (newQuestion !== oldQuestion) {
                        render = true;
                        message.info(`${createUserName} 更新了自定义问题 ${oldIndex + 1}`);
                    }
                    if (oldAnswerContent !== newAnswerContent) {
                        render = true;
                        message.info(`${createUserName} 更新了自定义问题 ${oldIndex + 1} 的新员工答复`);
                    }
                    nextFormList[oldIndex] = {
                        ...old,
                        question: newQuestion,
                        answer: {
                            ...oldAnswer,
                            answerContent: newAnswerContent
                        }
                    };
                }
            });
            const removed = [];
            // 移除删除的
            nextFormList = nextFormList.filter((old, index) => {
                const parse = old.isEqual || ret.findIndex(current => current.id === old.id) !== -1;
                if (!parse) {
                    render = true;
                    removed.push({
                        number: index + 1,
                        createUserName: old.createUserName
                    });
                }
                return parse;
            });
            removed.forEach(item => {
                message.info(`${item.createUserName} 删除了自定义问题 ${item.number}`);
            });
            if (render) {
                setFieldsValue({
                    interviewQuestions: nextFormList
                });
            }
        }
    });

    const getInfo = async () => {
        try {
            // 取完数据后启动轮询
            runPolling();
            console.log('面试准备数据', data);
            let { selfInterviewQuestions = [], othersInterviewQuestions = [] } = interviewPrepareVO || {};
            selfInterviewQuestions = selfInterviewQuestions.map(item => {
                const comment = formatComment(item.comments);
                return {
                    ...item,
                    comment,
                    answer: item.answer || {},
                    isAnswerEdit: !item?.answer?.answerContent,
                    isCommentEdit: !comment?.commentContent,
                    isEqual: true
                };
            });
            othersInterviewQuestions = othersInterviewQuestions.map(item => {
                const comment = formatComment(item.comments);
                return {
                    ...item,
                    comment,
                    answer: item.answer || {},
                    isCommentEdit: false
                };
            });
            setFieldsValue({
                interviewQuestions: [...selfInterviewQuestions, ...othersInterviewQuestions]
            });
        } catch (e) {
            console.log(e);
        }
    };

    useEffect(() => {
        message.config({
            maxCount: 100
        });
        getInfo();
        // 临时解决：录音启动后退出页面无法继续录音的操作
        resetInterviewRecordState(arrangeId);
        return () => {
            cancelPolling();
            // 在request.js中有对这个做限制，把它还原
            message.config({
                maxCount: 1
            });
        };
    }, []);

    const { message: msg, renderButton } = usePrepareAlert(map[period] ?? 'W', data, 'record');
    return (
        <div ref={scrollWrapRef}>
            <PrepareAlert message={msg} renderButton={renderButton} />
            <Collapse bordered={false} activeKey={activeKey} onChange={onChange}>
                <Panel header="新员工面谈安排" key="1">
                    <ArrangeDetail data={probationInterviewArrangeVO} />
                    <FormLayout type="col2">
                        <Form.Item label="面谈录音">
                            <div style={{ width: 115 }}>
                                <RecordButton
                                    cRef={recordButtonRef}
                                    scrollWrapRef={scrollWrapRef}
                                    getRecordState={() => getRecordState(0)}
                                    onChangeRecordState={onChangeRecordState}
                                    hintList={hintList}
                                />
                            </div>
                        </Form.Item>
                    </FormLayout>
                </Panel>
                <Panel header="自定义问题" key="2">
                    {getFieldDecorator('interviewQuestions', {
                        initialValue: []
                    })(<Question form={form} getRecordState={() => getRecordState(1)} arrangeId={arrangeId} />)}
                </Panel>
                <Panel header="面谈评估" key="3">
                    <Evaluation form={form} conclusions={generateRecordConclusionOption(interviewType)} />
                </Panel>
            </Collapse>
            <BottomAction openAll={openAll} data={data} form={form} params={getSubmitValues} />
        </div>
    );
};

export default Form.create()(Record);
